﻿using System.Data.Entity;
using System.Data.Entity.ModelConfiguration.Conventions;
using Legazpi.Payroll.DataAccess.DataObjects;


namespace Legazpi.Payroll.DataAccess.Context
{
    public class PayrollDataContext : DbContext
    {
        public DbSet<User> Users { get; set; }
        public DbSet<Role> Roles { get; set; }
        public DbSet<Employee> Employees { get; set; }
        public DbSet<Client> Clients { get; set; }
        public DbSet<Sector> Sectors { get; set; }
        public DbSet<Position> Positions { get; set; }
        public DbSet<PhilHealthTable> PhilHealthTable { get; set; }
        public DbSet<SSSTable> SSSTable { get; set; }        
        public DbSet<PayrollDate> PayrollDate { get; set; }
        public DbSet<Pharaphernalia> Pharaphernalia { get; set; }
        public DbSet<Adjustment> Adjustment { get; set; }
        public DbSet<Settings> Settings { get; set; }
        public DbSet<DayTimeRecord> DayTimeRecords { get; set; }
        public DbSet<EmployeeAdjustment> EmployeeAdjustments { get; set; }
        public DbSet<PayrollSummary> PayrollSummaries { get; set; }
        public DbSet<Contribution> Contributions { get; set; }
        public DbSet<GlobalAdjustment> GlobalAdjustments { get; set; }
        public DbSet<Detachment> Detachments { get; set; }
        

        public PayrollDataContext(string connectionString)
            : base(connectionString)
        {

        }
        
        
        protected override void OnModelCreating(DbModelBuilder modelBuilder)
        {
            modelBuilder.Conventions.Remove<PluralizingTableNameConvention>();
            

            modelBuilder.Entity<User>()
              .HasMany(u => u.Roles)
              .WithMany(r => r.Users)
              .Map( m =>
               {
                    m.MapLeftKey("UserId");
                    m.MapRightKey("RoleId");
                    m.ToTable("UserRoles");
               });

            modelBuilder.Entity<Position>()
                .HasMany(p => p.Employees)
                .WithOptional(e => e.Position)
                .HasForeignKey(e => e.PositionId)
                .WillCascadeOnDelete(false);

            modelBuilder.Entity<Employee>()
                .HasMany(ps => ps.PayrollSummaries)                
                .WithRequired(ps => ps.Employee)
                .HasForeignKey(ps => ps.EmployeeId);

            modelBuilder.Entity<PayrollDate>()
                .HasMany(ps => ps.PayrollSummaries)
                .WithRequired(ps => ps.PayRoll)
                .HasForeignKey(ps => ps.PayRollId);

        }
    }
}
